<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQueryByCustomerName(queryParams.customerName)"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryByCustomerName(queryParams.customerName)">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['customer:customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          @click="sendsale"
        >发送优惠券</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户ID" prop="customerId" width="120" />
      <el-table-column label="客户名称" prop="customerName" width="150" />
      <el-table-column label="用户分组" prop="groupName" width="150" />
      <el-table-column label="用户标签" prop="tagsName" width="150" />
      <el-table-column label="推荐人" prop="referrer" width="150" />
      <el-table-column label="手机号" prop="phoneNum" width="150" />
      <el-table-column label="余额" prop="balance" width="120" />
      <el-table-column label="积分" prop="score" width="120" />
      <el-table-column label="状态" prop="status" width="120" sortable>
        <template slot-scope="scope">
          <div class="status-switch">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </div>
          <div class="status-text">
            {{ scope.row.states }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['customer:customer:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDetails" icon="el-icon-circle-check"
                                v-hasPermi="['customer:customer:edit']">账户详情</el-dropdown-item>
              <el-dropdown-item command="handleSetGroup" icon="el-icon-user"
                                v-hasPermi="['customer:customer:edit']">设置分组</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页器 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <!-- 其他表单项 -->
        <el-form-item label="用户分组" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择">
            <el-option
              v-for="group in groups"
              :key="group.groupId"
              :label="group.groupName"
              :value="group.groupId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户标签" prop="tagsId">
          <el-select v-model="form.tagsId" placeholder="请选择" multiple collapse-tags name="tagsId">
            <el-option
              v-for="tag in tags"
              :key="tag.tagId"
              :label="tag.tagName"
              :value="tag.tagId"
              :selected="form.tagsId.includes(tag.tagId)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推荐人" prop="referrer">
          <el-input v-model="form.referrer" placeholder="请输入推荐人" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNum">
          <el-input v-model="form.phoneNum" placeholder="请输入手机号码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
    <!-- 设置分组弹窗 -->
    <el-dialog :title="title" :visible.sync="showGroupDialog" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 表单项 -->
        <el-form-item label="用户分组" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择">
            <el-option
              v-for="group in groups"
              :key="group.groupId"
              :label="group.groupName"
              :value="group.groupId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
    <!-- 用户详情弹窗 -->
    <el-dialog :title="form.customerName + '的详情'" :visible.sync="showDetailDialog" width="500px" append-to-body>
      <div class="customer-details">
        <p><strong>客户名称：</strong>{{ form.customerName }}</p>
        <p><strong>顾客分组名称：</strong>{{ form.groupName }}</p>
        <p><strong>标签名称：</strong>{{ form.tagsName }}</p>
        <p><strong>推荐人：</strong>{{ form.referrer }}</p>
        <p><strong>手机号：</strong>{{ form.phoneNum }}</p>
        <p><strong>余额：</strong>{{ form.balance }}</p>
        <p><strong>积分：</strong>{{ form.score }}</p>
        <p><strong>顾客状态：</strong>{{ form.status }}</p>
        <p><strong>顾客备注：</strong>{{ form.remark }}</p>

        <!-- 其他用户信息字段 -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDetailDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>




<script>
import {
  listCustomers,
  addCustomer,
  updateCustomer,
  deleteCustomerById,
  changeCustomerStatus,
  searchCustomers
} from "@/api/customer/customer";
import {
  listCustomerGroup,
} from "@/api/customer/group";
import {
  listCustomerTag,
} from "@/api/customer/tag";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";



export default {
  name: "CustomerIndex",
  data() {
    return {
      showDetailDialog: false,
      //分组数据
      groups: [],
      //标签数据
      tags: [],
      loading: true,
      customerList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: undefined
      },
      total: 0,
      single: true,
      multiple: true,
      open: false,
      showGroupDialog: false,
      title: "",
      form: { // 初始化顾客表单项，根据实际字段类型和默认值进行设置
        status:"0",
        customerName: "",
        groupName: "",
        groupId: "",
        tagId: "",
        tagName: "",
        tagsId: "",
        tagsName: "",
        balance:"",
        referrer: "",
        // 添加其他顾客信息的表单项
      },
      rules: {
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        phoneNum: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' }
        ]
      },
      showSearch: true ,// 添加showSearch属性并设置初始值
      options: []
    };
  },

  created() {
    this.getList();

  },
  methods: {
    handleCommand(command, row) {
      if (command === 'handleDetails') {
        this.handleDetails(row); // 调用处理账户详情的方法，并传入相应的数据
      } else if (command === 'handleSetGroup') {
        this.handleSetGroup(row); // 调用处理设置分组的方法，并传入相应的数据
      }
    },
    handleDetails(row) {
      this.form = row; // 存储选中的用户信息
      this.showDetailDialog = true; // 打开用户详情弹窗
    },
    closeDetailDialog() {
      this.showDetailDialog = false; // 关闭用户详情弹窗
      this.form = {}; // 清空选中的用户信息
    },
    handleSetGroup(row) {
      // debugger
      this.form = Object.assign({}, row);
      this.getGroups();
      // debugger
      // this.open = true;
      this.showGroupDialog = true;
      this.title = "设置分组";
      // 其他逻辑...
    },


    getGroups() {
      listCustomerGroup(this.queryParams)
        .then(groupRes => {
          if (groupRes.code === 200) {
              this.groups = groupRes.rows;
              this.options = [
                ...this.groups.map(group => ({
                  value: group.groupId,
                  label: group.groupName
                }))
              ];
          } else {
            this.$message.error("获取选项失败");
          }
        })
        .catch(error => {
          this.$message.error("请求出错");
          console.error(error);
        });
    },

    getOptions() {
      Promise.all([listCustomerGroup(this.queryParams), listCustomerTag(this.queryParams)])
        .then(([groupRes, tagRes]) => {

          if (groupRes.code === 200 && tagRes.code === 200) {
              this.groups = groupRes.rows;
              this.tags = tagRes.rows;
              this.options = [
                ...this.groups.map(group => ({
                  value: group.groupId,
                  label: group.groupName
                })),
                ...this.tags.map(tag => ({
                  value: tag.tagId,
                  label: tag.tagName
                }))
              ];
          } else {
            this.$message.error("获取选项失败");
          }
        })
        .catch(error => {
          this.$message.error("请求出错");
          console.error(error);
        });
    },

    handleQueryByCustomerName(customerName) {
      this.queryParams.pageNum = 1;
      this.queryParams.customerName = customerName;
      this.loading = true;
      searchCustomers(this.queryParams).then(response => {
       // 调用 searchCustomers 接口
        if (response.code === 200) {
          this.customerList = response.rows;
          this.total = response.total;
          this.loading = false;
        } else {
          this.$message.error(response.msg);
        }
      }).catch(error => {
        this.$message.error('请求出错');
        console.error(error);
      });
    },

    getList() {
      this.loading = true;
      listCustomers(this.queryParams).then(response => {
        if (response.code === 200) {
          this.customerList = response.rows;
          this.total = response.total;
          this.loading = false;
        } else {
          this.$message.error(response.msg);
        }
      }).catch(error => {
        this.$message.error('请求出错');
        console.error(error);
      });
    },

    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.customerName + '"顾客吗？').then(function() {
        return changeCustomerStatus(row.customerId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = !row.status
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      if (this.$refs.queryForm && this.$refs.queryForm.resetFields) {
        this.$refs.queryForm.resetFields();
      }
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.single = selection.length !== 1;
      this.multiple = selection.length === 0;
    },
    handleAdd() {
      this.resetForm();
      this.getOptions();
      this.open = true;
      this.title = "新增客户";
    },
    handleUpdate(row) {
      this.form = Object.assign({}, row);
      this.getOptions();
      this.open = true;
      this.title = "修改客户";
    },
    cancel() {
      this.open = false;
      this.resetForm();
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.customerId) {
            // 将布尔值转换为字符串
            this.form.status = this.form.status ? "0" : "1";
            // 执行修改操作
            this.form.tagsId = Array.isArray(this.form.tagsId) ? this.form.tagsId.join(",") : this.form.tagsId;
            updateCustomer(this.form)
              .then(() => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
                // 添加新的逻辑代码
                this.handleSetGroup(this.form); // 调用处理设置分组的方法，并传入相应的数据
                this.showGroupDialog = false;
              })
              .catch(error => {
                this.$message.error("修改失败");
                console.error(error);

              });
          } else {
            this.form.tagsId = Array.isArray(this.form.tagsId) ? this.form.tagsId.join(",") : this.form.tagsId;
            // 将布尔值转换为字符串
            this.form.status = this.form.status ? "0" : "1";
            // 执行新增操作
            addCustomer(this.form)
              .then(() => {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
                // 添加新的逻辑代码
                this.handleSetGroup(this.form); // 调用处理设置分组的方法，并传入相应的数据
              })
              .catch(error => {
                this.$message.error("新增失败");
                console.error(error);
              });
          }
        }
      });
    },


    handleDelete(row) {
      this.$confirm("确认删除该客户？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const customerId = [row.customerId];
          deleteCustomerById(customerId, "post").then(() => {
            this.$message.success("删除成功");
            this.getList();
          });
        })
        .catch(() => {});
    },
    resetForm() {
      if (this.$refs.form && this.$refs.form.resetFields) {
        this.$refs.form.resetFields();
      }
      this.form = {
        // 重置顾客表单项
        customerName: "",
        groupId: "",
        tagsId: "",
        referrer: "",
        remark: "",
        status: "0",
        // 重置其他顾客信息字段
      };
    }
  }
};
</script>
<style>
@import "~element-ui/lib/theme-chalk/select.css";
@import "~element-ui/lib/theme-chalk/option.css";
</style>
